
const path = require('path');
const config = require('./config');
const glob = require('glob');
const { log } = require('./utils');

// add url-route in /controllers:
function addMapping (app, mapping) {
  let reqPath, method;
  for (const url in mapping) {
    if (url.startsWith('GET ')) {
      method = 'GET';
      reqPath = url.substring(4);
      app.get(config.rootPath + reqPath, mapping[url]);
    } else if (url.startsWith('POST ')) {
      method = 'POST';
      reqPath = url.substring(5);
      app.post(config.rootPath + reqPath, mapping[url]);
    } else if (url.startsWith('PUT ')) {
      method = 'PUT';
      reqPath = url.substring(4);
      app.put(config.rootPath + reqPath, mapping[url]);
    } else if (url.startsWith('DELETE ')) {
      method = 'DELETE';
      reqPath = url.substring(7);
      app.del(config.rootPath + reqPath, mapping[url]);
    } else {
      console.error(`invalid URL: ${url}`);
    }
    if (method) {
      log(`注册url: ${method} ${config.rootPath + reqPath}`);
    }
  }
}

function addControllers (app, dir) {
  glob(path.resolve(__dirname, dir, '**'), (err, files) => {
    if (err) return;
    files.filter(file => file.endsWith('index.js'))
      .forEach(f => {
        log(`读取控制器： ${f}`);
        addMapping(app, require(f));
      });
  });
}

module.exports = function (dir) {
  const controllersDir = dir || 'controllers';
  const app = require('express')();
  addControllers(app, controllersDir);
  return app;
};
